import threading
import time
import mc

debug = False

def update_background_image():
	"""
	Looping function to update the background image
	
	ToDo:
		Build art list from current Plex Media Server folder, if list is empty default to folder default art, if missing last resort to black.png
	"""
	background_art_images = ["0", "/library/metadata/22206/art?t=1344350649", "/library/metadata/3353/art?t=1344049742", "/library/metadata/22241/art?t=1345349098", "/library/metadata/22238/art?t=1344930198", "/library/metadata/22207/art?t=1344364412", "/library/metadata/3341/art?t=1344049610"]

	while True:
		i = int(background_art_images[0]) + 1

		background_image_texture_path = "http://" + plexMediaServer_Address + ":" + plexMediaServer_Port + background_art_images[i]
		background_image.SetTexture(background_image_texture_path)

		if debug : mc.ShowDialogOk("Background Art", "len(background_art_images):  " + str(len(background_art_images)) + "\ni:  " + str(i) + "\nbackground_art_images[0]:  " + background_art_images[0])

		if (i + 1) == len(background_art_images):
			background_art_images[0] = "0"
		else:
			background_art_images[0] = str(i)

		if debug : mc.ShowDialogOk("Background Art", "len(background_art_images):  " + str(len(background_art_images)) + "\ni:  " + str(i) + "\nbackground_art_images[0]:  " + background_art_images[0])

		time.sleep(10)


mc.ActivateWindow(14000)

config = mc.GetApp().GetLocalConfig()
main_window = mc.GetWindow(14000)

#Build this out to support more than just one Plex Media Server
plexMediaServer_Address = config.GetValue("plexMediaServer_Address")
plexMediaServer_Port = config.GetValue("plexMediaServer_Port")

while plexMediaServer_Address == "" : plexMediaServer_Address = mc.ShowDialogKeyboard("Plex Media Server Address:", "192.168.2.10", False)
config.SetValue("plexMediaServer_Address", plexMediaServer_Address)

while plexMediaServer_Port == "" : plexMediaServer_Port = mc.ShowDialogKeyboard("Plex Media Server Port:", "32400", False)
config.SetValue("plexMediaServer_Port", plexMediaServer_Port)

if debug : mc.ShowDialogOk("Plex Media Server", plexMediaServer_Address + ":" + plexMediaServer_Port)


background_image = main_window.GetImage(1000)

update_thread = threading.Thread(target=update_background_image)
update_thread.daemon = True
update_thread.start()